package br.com.ctm.advogadope.rest.impl;

import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import br.com.ctm.advogadope.model.Usuario;
import br.com.ctm.advogadope.negocio.api.UsuarioNegocio;
import br.com.ctm.advogadope.rest.api.AutenticacaoResource;
import br.com.framework.util.security.CryptoUtils;

@Path("auth")
@Named
public class AutenticacaoResourceImpl implements AutenticacaoResource {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Context
	protected UriInfo uriInfo;

	@Context
	private HttpServletRequest servletRequest;
	
	@Inject
	private UsuarioNegocio usuarioNegocio;

	public AutenticacaoResourceImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	@POST
	@Path("login")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Response login(@FormParam("email") @DefaultValue("") String email, @FormParam("senha") @DefaultValue("") String senha) {
		Usuario usuEx = usuarioNegocio.findByEmail(email);
		Response response = null;
		if (usuEx != null) {
			if (usuEx.getSenha().equals(CryptoUtils.getEncryptedSha1(senha))) {
				response = Response.ok().build();
			} else {
				response = Response.status(javax.ws.rs.core.Response.Status.UNAUTHORIZED).build();
			}
		} else {
			response = Response.noContent().build();
		}
		return response;
		/*
		try {
			if (servletRequest.getUserPrincipal() == null)  {
				servletRequest.login(email, CryptoUtils.getEncryptedSha1(senha));
				servletRequest.getSession(true);
			}
			return Response.ok().build();
		} catch (ServletException e) {
			return Response.status(javax.ws.rs.core.Response.Status.UNAUTHORIZED).build();
		}*/
	}

	@Override
	@GET
	@Path("logout")
	public Response logout() throws SecurityException {
		try {
			servletRequest.logout();
			return Response.ok().build();
		} catch (ServletException e) {
			return Response.serverError().build();
		}
	}

}
